// utils/ocr/enter.go
package ocr

import (
	"bytes"
	"encoding/json"
	"muziai-server/global"

	"fmt"
	"github.com/sirupsen/logrus"
	"io"
	"mime/multipart"
	"net/http"
	"os"
)

type OcrResponse struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
	Data struct {
		RawOut      [][]interface{} `json:"raw_out"`
		SpeedTime   float64         `json:"speed_time"`
		ImgDetected string          `json:"img_detected"`
	} `json:"data"`
}

func Ocr(imagePath string) (out string, err error) {
	url := global.Config.Ocr.Url
	bodyBuf := &bytes.Buffer{}
	bodyWrite := multipart.NewWriter(bodyBuf)
	// 读取文件
	file, err := os.Open(imagePath)
	if err != nil {
		logrus.Error(err)
		return
	}
	defer file.Close()

	// 创建一个新的file
	fileWrite, err := bodyWrite.CreateFormFile("file", imagePath)
	// 将上面的file放入现在的file
	_, err = io.Copy(fileWrite, file)
	if err != nil {
		logrus.Error(err)
		return
	}
	bodyWrite.WriteField("compress", fmt.Sprintf("%d", global.Config.Ocr.Compress))
	bodyWrite.Close()
	contentType := bodyWrite.FormDataContentType()
	response, err := http.Post(url, contentType, bodyBuf)
	if err != nil {
		logrus.Error(err)
		return
	}

	byteData, _ := io.ReadAll(response.Body)
	var data OcrResponse
	err = json.Unmarshal(byteData, &data)
	if err != nil {
		logrus.Error(err)
		return
	}

	for _, i2 := range data.Data.RawOut {
		out += i2[1].(string)
	}

	return
}
